import axios from "axios";
import qs from "qs";
import { ElMessage } from "element-plus";

// 设置基础请求地址
// axios.defaults.baseURL = 'https://www.web80.cc'  // 正式
axios.defaults.baseURL = "http://localhost:3333"; // 开发

// 设置超时超时
axios.defaults.timeout = 10000;

// 这边由于后端没有区分测试和正式，姑且都写成一个接口。
// axios.defaults.baseURL = config[import.meta.env.MODE].baseUrl;

// 设置post请求头
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";

// 请求拦截
axios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = "Bear " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截
axios.interceptors.response.use(
  (response) => {
    if (response.status == 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    alert(`异常请求：${JSON.stringify(error.message)}`);
  }
);

// 封装post请求和get请求
export const post = (url, data) => {
  return new Promise((resolve, reject) => {
    axios({
      method: "post",
      url,
      data: qs.stringify(data),
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export const get = (url, data) => {
  return new Promise((resolve, reject) => {
    axios({
      method: "get",
      url,
      params: data,
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
